package com.zs.backend.common.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class OSSService {

    @Autowired
    private OSS ossClient;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.file.expiration}")
    private long expiration;

    @Value("${oss.endpoint}")
    private String endpoint;


    public String filePath(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;
        String filePath = fileName;
        return filePath;
    }

    public String upload(MultipartFile file, String filePath) {
        String url = "";
        try{
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());

            PutObjectRequest request = new PutObjectRequest(bucketName, filePath, file.getInputStream(), metadata);
            ossClient.putObject(request);
            url = "https://" + bucketName + "." + endpoint + "/" + filePath;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //ossClient.shutdown();
        }

        return url;
    }


    public void deleteFile(String objectName) {
        try {
            // 删除文件
            ossClient.deleteObject(bucketName, objectName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭 OSS 客户端
            //ossClient.shutdown();
        }
    }
}

